package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;

public class Servlet extends HttpServlet {
    private HashMap hm = new HashMap<String,String>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String realPath = getServletContext().getRealPath("/user.txt");
        //使用getServletContext().getRealPath()获取的是web文件夹下面编译后资源文件的真实路径
        //使用类加载器.getResourse.Path
        BufferedReader br = new BufferedReader(new FileReader(realPath));
        String s;
        while ((s=br.readLine())!=null){
            String[] split = s.split(":");
            hm.put(split[0],split[1]);
        }
        String id = req.getParameter("id");
        String psw = req.getParameter("psw");
        if (hm.containsKey(id)){
            System.out.println(hm.get(id));
            if (hm.get(id).equals(psw)){
                resp.getWriter().write("登陆成功!");
            }else{
                resp.getWriter().write("登陆失败,账号密码错误");
            }
        }else{
            resp.getWriter().write("登陆失败,账号不存在");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
